const express = require('express');

const AccountModel = require('../../module/accountModel');
const moment = require('moment')
const checkLoginMiddleware = require('../../middleware/checkLogin')

const router = express.Router();


router.get('/',(req,res)=>{
  res.redirect('/account')
})

/* GET home page. */
router.get('/account', checkLoginMiddleware,function (req, res, next) {
  // let accounts = db.get('account').value()
  // console.log(accounts)
  AccountModel.find().sort({ time: -1 }).exec((err, data) => {
    if (err) {
      res.status(500).send('查询失败')
      return
    }
    res.render('list', { accounts: data, moment: moment })
  })
});

router.get('/account/create', checkLoginMiddleware,(req, res) => {
  res.render('create')
})

router.post('/account', checkLoginMiddleware,function (req, res, next) {
  // db.get('account').unshift({id:shortid.generate(),...req.body}).write()
  // console.log(req.body)
  AccountModel.create({
    ...req.body,
    time: moment(req.body.time).toDate()
  }, (err, data) => {
    if (err) {
      res.status(500).send('插入失败')
      return
    }
    res.render('success', { msg: '添加成功哦～～', url: '/account' })
  })
});

router.get('/delete/:id', checkLoginMiddleware,(req, res) => {
  let id = req.params.id
  // db.get('account').remove({id:id}).write()
  AccountModel.deleteOne({ _id: id }, (err, data) => {
    if (err) {
      res.status(500).send('删除失败')
      return
    }
    res.render('success', { msg: '删除成功哦～～', url: '/account' })

  })
})

module.exports = router;
